<template>
  <view class="center">
    <div class="backIcon" @click="backHome">
      <IconFont name="rect-left" color="#342e2c" size="18"></IconFont>
    </div>
    <div class="mapCard">
      <div id="mapSettlement" class="mapSettlement" v-if="showMap"></div>
      <div id="my-panel"></div>
    </div>
    <div class="floatCardAddressList">
      <div class="CarSelect">
        <div class="CarSelectIcon"><img :src="diverCar" /></div>
        <div class="CarSelectBtn" @click="toSelectCar">选择车辆</div>
      </div>

      <div class="CarHasInfo" v-if="false">
        <div class="CarInfoLeft">
          <div class="infoOne">
            <div>车牌号: 新A23984</div>
            <div>驾驶员: 张三</div>
          </div>
          <div class="infoTwo">
            <div>车辆类型:</div>
            <div>驾驶员信息:</div>
          </div>
        </div>
        <div class="CarInfoRight">
          <span class="smallText">预计</span>
          <span class="bigText">20.32</span>
          <span class="smallText">元</span>
        </div>
      </div>
      <div class="CarNoInfo">
        <img :src="noSelectCar" alt="" width="100%" height="100%" />
      </div>
      <div class="timeSelect" @click="openTimeSelect">
        现在出发<IconFont name="rect-right" color="#342e2c" size="11" style="margin-left: 5px"></IconFont>
      </div>
      <div class="carBtn">用车申请</div>
    </div>
    <timeSelectPage ref="timeSelectRef"></timeSelectPage>
    <carSelectPage ref="carSelectRef"></carSelectPage>
  </view>
</template>
<script lang="js" setup name="MapDialog">
import {
  ComponentInternalInstance,
  getCurrentInstance,
  onMounted,
  ref,
  shallowRef,
  toRaw,
  defineEmits,
  nextTick
} from "vue";
import Taro, { eventCenter, useDidShow, useDidHide } from '@tarojs/taro';
import { IconFont } from '@nutui/icons-vue-taro';
import diverCar from '../../svgs/diverCar.svg';
import AMapLoader from "@amap/amap-jsapi-loader";
import noSelectCar from '../../svgs/noSelectCar.svg';
import timeSelectPage from '../../components/timeSelect/timeSelect.vue';
import carSelectPage from '../../components/carSelect/carSelect.vue';


const showMap = ref(false)
const MAP_KEY = "39cae8cb35cd12d8c605f324788e3040";
const MAP_CODE = "af5a7657629f4653a0e39888ed6c75e1";
const emits = defineEmits('mapSelectAddress');

const mapAddress = ref()
const timeSelectRef = ref()
const carSelectRef = ref()

// 地图实例对象
const AMapInstance = shallowRef(null);
const marker = shallowRef();
/**
 * 初始化地图
 * @return {Promise<void>}
 */
async function initMap() {
  showMap.value = true
  try {
    if (AMapInstance.value !== null) {
      AMapInstance.value.clearMap();
    }
    await AMapLoader.load({
      key: MAP_KEY,
      // 安全密钥
      securityJsCode: MAP_CODE,
      version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      plugins: [
        "AMap.Autocomplete",
        "AMap.Geolocation",//定位
        "AMap.Geocoder",// 地址解析
        "AMap.Driving",//驾车规划
      ], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
    })
    AMapInstance.value = new AMap.Map("mapSettlement", {
      //设置地图容器id
      viewMode: "3D", //是否为3D地图模式
      zoom: 16, //初始化地图级别
      center: [87.630238, 43.859831], //初始化地图中心点位置
    });
    //绑定地图移动与缩放事件
    AMapInstance.value.on('dragging', logMapInfo);
    getDrivingData()
    // 自己本身定位
    addMyAddressMarker()
  } catch (err) {
    console.warn(err);
  }


}


// 驾车地理规划
function getDrivingData() {


  console.log(Taro.getCurrentInstance().preloadData)
  let startLngLat = Taro.getCurrentInstance().preloadData.addressList.start.location.split(',')
  let endLngLat = Taro.getCurrentInstance().preloadData.addressList.end.location.split(',')
  let opts = {
    //途经点参数，最多支持传入16个途经点
    waypoints: [],
  };
  if (Taro.getCurrentInstance().preloadData.addressList.first.location.length > 0) {
    opts.waypoints.push(Taro.getCurrentInstance().preloadData.addressList.first.location.split(','))
  } if (Taro.getCurrentInstance().preloadData.addressList.second.location.length > 0) {
    opts.waypoints.push(Taro.getCurrentInstance().preloadData.addressList.second.location.split(','))
  }

  console.log(startLngLat, endLngLat, opts)
  const driving = new AMap.Driving({
    map: AMapInstance.value,
    panel: "my-panel",
  });
  //获取起终点规划线路
  driving.search(startLngLat, endLngLat, opts, function (status, result) {
    if (status === "complete") {
      //status：complete 表示查询成功，no_data 为查询无结果，error 代表查询错误
      //查询成功时，result 即为对应的驾车导航信息
      console.log(result);
      //       start_location (LngLat) : 此路段起点
      // end_location (LngLat) : 此路段终点
      // instruction (string) : 此路段说明，如“沿北京南站路行驶565米右转”
      // action (string) : 本驾车子路段完成后动作
      // assist_action (string) : 驾车子路段完成后辅助动作，一般为到达某个目的地时返回
      // orientation (string) : 驾车方向
      // road (string) : 驾车方向
      // distance (number) : 此路段距离，单位：米
      // tolls (number) : 此段收费，单位：元
      // tolls_distance (number) : 收费路段长度，单位：米
      // toll_road (string) : 主要收费道路
      // time (number) : 此路段预计使用时间，单位：秒
      // path (Array<LngLat>) : 此路段坐标集合
    } else {
      console.log("获取驾车数据失败：" + result);
    }
  });
}

/**
 * 地图逆地理编码插件
 * @param LngLat
 */
function getAddress(LngLat) {
  const geoCoder = new AMap.Geocoder({
    city: '乌鲁木齐'
  });
  return new Promise((resolve, reject) => {
    geoCoder.getAddress(LngLat, (status, result) => {
      if (status === 'complete' && result.info === 'OK') {
        resolve(result);
      } else {
        reject(result);
      }
    });
  });
}
/**
 * 添加我的地址标记
 */
function addMyAddressMarker() {
  marker.value = new AMap.Marker(); // 创建标记对象
  marker.value.setPosition([87.630238, 43.859831]); // 设置标记位置
  AMapInstance.value.add(marker.value); // 将标记添加到地图实例中
  getAddress([87.630238, 43.859831]).then((res) => {
    mapAddress.value = replaceField(res.regeocode)

  })
}

function replaceField(data) {
  console.log(data)
  // 通过方法去除存在字段
  var noProvince = data.formattedAddress.replace(new RegExp(data.addressComponent.province, "g"), "");
  var noCity = noProvince.replace(new RegExp(data.addressComponent.city, "g"), "");
  var noDistrict = noCity.replace(new RegExp(data.addressComponent.district, "g"), "");
  var address = noDistrict.replace(new RegExp(data.addressComponent.township, "g"), "");

  return address
}
//显示地图层级与中心点信息
function logMapInfo() {
  let zoom = AMapInstance.value.getZoom(); //获取当前地图级别
  let center = AMapInstance.value.getCenter(); //获取当前地图显示中心位置


};
// 添加一个浮标

function floatInfoWindow(zoom) {
  var content = [
    `<div style='display:flex;flex-flow:column;align-items:center;width:150px;height:120px;'>
    <div class='infoPao' style='min-width: 100px; min-height: 20px;border: 1px solid #000; background-color: #fff;text-align: center;padding: 2px;font-size:14px;border-radius: 10px;'>${mapAddress.value}</div>
    <div style='width:2px;height:30px;background-color:#000;'>
      </div>
      <div style='width:10px;height:10px;background-color:#ffb114;border-radius:50%;margin:0 auto;'><div>
      </div>
  `,
  ];
  var infoWindow = new AMap.InfoWindow({
    isCustom: true, //使用自定义窗体
    content: content.join("<br>"),
    offset: new AMap.Pixel(0, 0),
  });

  infoWindow.open(AMapInstance.value, AMapInstance.value.getCenter());
}

function openTimeSelect() {
  timeSelectRef.value.openShow()
}
function toSelectCar() {
  carSelectRef.value.openShow()

}
function toInitMap() {
  nextTick(() => {

    initMap();
  })
}

function backHome() {
  Taro.navigateTo({
    url: '/pages/index/index'
  })
}
function DidMap() {
  if (AMapInstance.value) {
    AMapInstance.value.destroy();
    AMapInstance.value = null;
  }
}
useDidHide(() => {
  DidMap()
  showMap.value = false
})
onMounted(() => {
  nextTick(() => {
    initMap();
  })
})
defineExpose({ toInitMap, DidMap });
</script>
<style lang="scss" scoped>
@import "./index.scss";
</style>
